import pymysql
from pymysql import cursors

from handlers.handler_files.handler_ini import HandlerIni
from handlers.handler_log import logger


class HandlerMysql:
    def __init__(self):
        try:
            self.handler = HandlerIni()
            self.conf = {
                'host': self.handler.get_mysql_value('host'),
                'port': int(self.handler.get_mysql_value('port')),
                'user': self.handler.get_mysql_value('user'),
                'password': self.handler.get_mysql_value('password'),
                'database': self.handler.get_mysql_value('database_name'),
                'charset': 'utf8'
            }
            # 获取连接
            self.conn = pymysql.connect(**self.conf)
            # 获取操作游标,cursor=cursors.DictCursor  将字段名输出
            self.cursor = self.conn.cursor(cursor=cursors.DictCursor)
            logger.trace(f"成功连接到数据库:{self.conf['database']}")
        except Exception as e:
            logger.trace(f"链接数据库失败，异常原因：{e}")

    def add(self, sql: str, fetchall: bool = False):
        """
        查询数据库数据
        :param sql: 查询sql语句
        :param fetchall:  是否查询全部数据，默认为false，不进行全部查询
        :return:结果
        """
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            if fetchall:
                return self.cursor.fetchall()
            else:
                return self.cursor.fetchone()
        except Exception as e:
            logger.exception(f"查询异常：{e}")

    def query(self, sql: str, fetchall: bool = False):
        """
        查询数据库数据
        :param sql: 查询sql语句
        :param fetchall:  是否查询全部数据，默认为false，不进行全部查询
        :return:结果
        """
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            if fetchall:
                result = self.cursor.fetchall()
                return result
            else:
                result = self.cursor.fetchone()
                return result
        except Exception as e:
            logger.exception(f"查询异常：{e}")
        finally:
            self.cursor.close()
            self.conn.close()


if __name__ == '__main__':
    conn = HandlerMysql()
    sql_1 = "select * from t_account where account_username = '123'"
    data = conn.query(sql_1)
    print(type(data), data)
